package cn.yunhe.service.impl;

import cn.yunhe.dao.ExamDao;
import cn.yunhe.entity.Exam;
import cn.yunhe.entity.User;
import cn.yunhe.service.ExamService;
import cn.yunhe.util.DateUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("examService")
public class ExamServiceImpl implements ExamService {

    @Resource
    private ExamDao examDao;

    @Override
    public List<Exam> getAllExam(Exam exam) {
        return examDao.getAllExam(exam);
    }

    @Override
    public int getExamCount(Exam exam) {
        return examDao.getExamCount(exam);
    }

    @Override
    public Page getExamByPage(Map<String, Object> map) {
        updAllExamAudit();
        Page page = new Page();
        //设置 总条数
        int totalNum = examDao.getExamCount((Exam) map.get("exam"));
        page.setTotal(totalNum);
        // 获取页大小
        int pageSize = (int) map.get("pageSize");
        // 获取当前页
        int currPage = map.get("currPage") == null ? 1 : (int) map.get("currPage");
        //计算总页数
        int totalPage = (totalNum / pageSize) + (totalNum % pageSize == 0 ? 0 : 1);
        page.setPageNum(totalPage);
        //启用分页
        page = PageHelper.startPage(currPage, pageSize);
        examDao.getAllExam((Exam) map.get("exam"));
        return page;
    }

    @Override
    public int updExamAudit(int id, int state) {
        Map<String, Object>map = new HashMap<>();
        map.put("id",id);
        map.put("state", state);
        return examDao.updExamAudit(map);
    }

    @Override
    public int updAllExamAudit() {
        Exam exam = new Exam();
        byte b = 1;
        exam.setApproved(b);
        List<Exam>list = examDao.getAllExam(exam);
        Date date = new Date();
        int count = 0;
        for(Exam e : list){
            if(date.getTime() >= (e.getEndTime()).getTime()){
                count += examDao.updAllExamAudit(e.getId());
            }
        }
        return count;
    }

    @Override
    public int addExam(Exam exam) {
        return examDao.addExam(exam);
    }

    public ExamDao getExamDao() {
        return examDao;
    }

    public void setExamDao(ExamDao examDao) {
        this.examDao = examDao;
    }
}
